//
//  SqliteManager.m
//  ZBaiduDemo
//
//  Created by 周成龙 on 16/10/26.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "SQLiteTool.h"
#import <sqlite3.h>

@implementation SQLiteTool
static SQLiteTool *_tool = nil;
sqlite3 *_db;

+ (instancetype)shareSQLiteTool {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _tool = [[SQLiteTool alloc] init];
    });
    return _tool;
}

// 打开数据库
- (BOOL)openDB {
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    filePath = [filePath stringByAppendingPathComponent:@"location.sqlite"];
    NSLog(@"path = %@", filePath);
    if (sqlite3_open(filePath.UTF8String, &_db) != SQLITE_OK) {
        NSLog(@"数据库打开失败");
        return NO;
    }
    return [self createTable];
}

- (BOOL)createTable {
    NSString *sql = @"create table if not exists 'l_table' ('l_id' integer not NULL primary key autoincrement, 'latitude' text, 'longitude' text, 'timeString' text);";
    return [self execSql:sql];
}

- (BOOL)execSql:(NSString *)sql {
    return sqlite3_exec(_db, sql.UTF8String, nil, nil, nil) == SQLITE_OK ? YES : NO;
}

// 查询数据
- (NSArray *)qureySqlite:(NSString *)querySql {
    
    sqlite3_stmt *stmt = nil;
    // 准备查询数据
    if (sqlite3_prepare_v2(_db, querySql.UTF8String, -1, &stmt, nil) != SQLITE_OK) {
        NSLog(@"数据查询失败");
        return nil;
    }
    
    // 准备成功，开始查询数据
    NSMutableArray *array = [NSMutableArray array];
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        
        int count = sqlite3_column_count(stmt);
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        for (int i = 0; i < count; i ++) {
            // 取出 i 位置上键
            const char *cKey = sqlite3_column_name(stmt, i);
            NSString *key = [NSString stringWithUTF8String:cKey];
            // 取出 i 位置上值
            const char *cValue = (const char *)sqlite3_column_text(stmt, i);
            NSString *value = [NSString stringWithUTF8String:cValue];
            [dict setValue:value forKey:key];
        }
        
        [array addObject:dict];
    }
    
    return array;
}

// 关闭数据库
- (void)closeDB
{
    sqlite3_close(_db);
}

@end
